
import React, { useRef, useEffect, useMemo, forwardRef, useImperativeHandle } from 'react';
import { InputProps as AntdInputProps } from 'antd/lib/input';
import { FormItemProps } from 'antd/lib/form';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import { defaultOptions, parsingStr } from './data';
import { getSource } from './api';

interface LinkInputProps extends AntdInputProps {
  url?: string;
  query?: string;
}

interface ChartsRefProps {
  getData(): any;
}
export interface ChartsProps extends CanvasItemProps {
  chartsProps: LinkInputProps;
  formItemProps: FormItemProps;
  initialValue?: any;
  scriptsChangeData?: any;
}

const echarts = (window as any).echarts;

const App = (props: ChartsProps, ref: React.Ref<ChartsRefProps>) => {
  const { chartsProps, formItemProps, initialValue, scriptsChangeData, isDesign, domComplete, getCurrInterceptors, ...canvasProps } = props;

  useQueryControlWrap(canvasProps.id, '', domComplete);

  const refs = useRef<any>(null);
  const counts = useRef<number>(0);
  const chartsRef = useRef<any>(null);
  const optionsRef = useRef<any>(null);
  const scriptOptionsRef = useRef(null);

  useImperativeHandle(ref, () => ({
    getData() {
      return optionsRef.current || {};
    },
    setData(_options: any) {
      if (_options) {
        scriptOptionsRef.current = _options;
        chartsRef.current.setOption(scriptOptionsRef.current);
      }
    }
  }));


  // eslint-disable-next-line react-hooks/exhaustive-deps
  const handleResult = (result: any) => {
    const currInterceptors = getCurrInterceptors?.(chartsProps?.url!);
    if (currInterceptors?.get) return currInterceptors.get(result, chartsProps?.query);
    return false;
  };

  const value = useMemo(() => {
    return scriptsChangeData[formItemProps.name as string] || undefined;
  }, [formItemProps.name, scriptsChangeData]);

  const query = useMemo(() => {
    try {
      return parsingStr(chartsProps.query!, scriptsChangeData);
    } catch (error) {
      return '{}';
    }
  }, [chartsProps.query, scriptsChangeData]);

  useEffect(() => {
    if (value && !!chartsRef.current) {
      chartsRef.current.setOption(value);
      optionsRef.current = value;
    }
  }, [value]);

  useEffect(() => {
    chartsRef.current = chartsRef.current || echarts.init(refs.current as any);

    if (scriptOptionsRef.current) {
      return chartsRef.current.setOption(scriptOptionsRef.current);
    }

    // 图表组件挂载一次resize方法到全局的chartsResize数组
    if (counts.current === 0 && !!chartsRef.current) {
      if ((window as any).chartsResize) {
        (window as any).chartsResize.push(chartsRef.current.resize);
      } else {
        (window as any).chartsResize = [chartsRef.current.resize];
      }
      counts.current = 1;
    }

    if (!chartsProps?.url) return;

    const currOption = defaultOptions[chartsProps.type!];

    if (isDesign) {
      chartsRef.current.setOption(currOption);
    } else {
      if (chartsProps.url) {
        getSource(chartsProps.url, JSON.parse(query)).then(res => {
          if (res) {
            const v = handleResult(res);

            if (v) chartsRef.current.setOption(scriptOptionsRef.current || v);
            else chartsRef.current.setOption(scriptOptionsRef.current || currOption);
          }
        });
      } else {
        chartsRef.current.setOption(currOption);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [chartsProps.type, chartsProps.url, query]);

  return (
    <div {...(canvasProps as any)} {...(formItemProps)} ref={refs}></div>
  );
};

export default forwardRef(App);


